import inquirer from 'inquirer';
import * as fs from 'fs';
import * as fse from 'fs-extra';

/**
 * 从命令行获取文字
 */
export async function getInput(message: string) {
  const res = await inquirer.prompt([
    {
      type: 'input',
      name: 'textInput',
      message,
    }
  ])
  return res.textInput;
}

/**
 * 命令行单选交互
 * @param msg 标题
 * @param options 选项
 * @param answer 答案
 */
export async function select<T extends string>(msg: string, options: { name: string, value: T }[], answer?: T): Promise<T> {
  let res = await inquirer.prompt({
    type: 'list',
    name: 'res',
    message: msg,
    choices: options,
    pageSize: 12
  }, { res: answer });
  return res.res;
}

/**
 * 新开一个命令行（进程）执行命令
 */
export { execSync } from 'child_process';

/**
 * 复制文件
 */
export function copyFile(sourceFilePath: string, targetFilePath: string) {
  if (fse.existsSync(targetFilePath)) {
    fs.rmSync(targetFilePath, { recursive: true });
  }
  fs.copyFileSync(sourceFilePath, targetFilePath);
}

/**
 * 设置软链接（用软链接代替复制文件夹）
 */
export function setSymlink(sourcePath: string, targetPath: string) {
  if (!fse.existsSync(targetPath)) {
    fse.ensureSymlinkSync(sourcePath, targetPath);
  }
}

/**
 * 设置硬链接
 */
export function setHardlink(sourcePath: string, targetPath: string) {
  if (!fse.existsSync(targetPath)) {
    fse.ensureLinkSync(sourcePath, targetPath);
  }
}

/**
 * 删除文件或目录
 */
export function deleteFileOrDir(path: string) {
  if (fse.existsSync(path)) {
    fs.rmSync(path, { recursive: true });
  }
}